<template>
  <div class="player" v-show="playList.length > 0">
    <transition name="normal"
                @enter="enter"
                @after-enter="afterEnter"
                @leave="leave"
                @after-leave="afterLeave"
    >
      <div class="player-normal" v-show="fullScreen">
        <div class="background">
          <img :src="currentSong.img" alt="">
        </div>
        <div class="top">
          <div class="back" @click="back">
            <i class="icon-back"></i>
          </div>
          <h1 class="title" v-html="currentSong.name"></h1>
          <h2 class="subtitle" v-html="currentSong.singer"></h2>
        </div>
        <div class="middle"
        @touchstart.prevent="middleTouchStart"
        @touchmove.prevent="middleTouchMove"
        @touchend="middleTouchEnd"
        >
          <div class="middle-l" ref="middleL">
            <div class="cd-wrapper" ref="cdWrapper" >
              <div class="cd">
                <img :src="currentSong.img" alt="" :class="addCls">
              </div>
            </div>
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{playingLyric}}</div>
            </div>
          </div>
          <div class="middle-r" ref="middleLyric">
            <scroll :data="currentLyric && currentLyric.lines" class="scroll-lyric" ref="lyricList">
            <div class="lyric-wrapper">
              <div v-if="currentLyric">
                <p class="text"
                ref="lineEls"
                :class="{'current': currentLineNum === index}"
                v-for="(line, index) of currentLyric.lines" :key="index">{{line.txt}}</p>
              </div>
            </div>
            </scroll>
          </div>
        </div>
        <div class="bottom" >
          <div class="dot-wrapper">
            <span class="dot" :class="{'active': currentShow === 'cd'}"></span>
            <span class="dot" :class="{'active': currentShow === 'lyric'}"></span>
          </div>
          <div class="progress-wrapper">
            <span class="time">{{formate(currentTime)}}</span>
            <div class="progress-bar-wrapper">
              <progress-bar :percent="percent" @changePercent="changePercent"></progress-bar>
            </div>
            <span class="time">{{durTime}}</span>
          </div>
          <div class="operators">
            <div class="icon i-left" @click="changeMode" >
              <i :class="iconMode"></i>
            </div>
            <div class="icon i-left"  :class="disableCls">
              <i class="icon-prev" @click="prevSong"></i>
            </div>
            <div class="icon i-center" :class="disableCls" >
              <i  @click="changePlay" :class="iconPlay"></i>
            </div>
            <div class="icon i-right"  :class="disableCls">
              <i class="icon-next" @click="nextSong"></i>
            </div>
            <div class="icon i-right">
              <i class="icon" @click.stop="toggleFavorite(currentSong)" :class="getFavoriteIcon(currentSong)"></i>
            </div>
          </div>
        </div>
      </div>
     </transition>
     <transition name="mini">
      <div class="player-mini" v-show="!fullScreen" @click="showFullScreen">
        <div class="icon">
          <img :src="currentSong.img" alt="" :class="addCls">
        </div>
        <div class="text">
          <h2 v-html="currentSong.name"></h2>
          <p v-html="currentSong.singer"></p>
        </div>
          <div class="control">
              <progress-circle :radius="radius" :percent="percent">
              <i class="icon-mini" :class="iconMiniPlay" @click.stop.prevent="changePlay"></i>
              </progress-circle>
          </div>
        <div class="control">
          <i class="icon-playlist" @click.stop="showPlaylist"></i>
        </div>
      </div>
    </transition>
    <playlist ref="playlist" @close="closePlaylist"></playlist>
    <audio
    src="http://ws.stream.qqmusic.qq.com/C400003NikJo0a0uzm.m4a?guid=8802204464&vkey=5EAEBA553D68CE772D2D86490B9A984E90242AC6C0C5FE4FD7DB2E08BCD4CE2F1F3442E5CA02C5D0F52139C1ACCF034D01972462265DA4AC&uin=0&fromtag=66"
    ref="audio"
    @play="canplay"
    @error="error"
    @timeupdate="updateTime"
    @ended="endSong"
    ></audio>
  </div>
</template>
<script>
import {mapGetters, mapMutations, mapActions} from 'vuex'
import animations from 'create-keyframe-animation'
import ProgressBar from 'base/progress-bar/progress-bar'
import ProgressCircle from 'base/progress-circle/progress-circle'
import {playMode} from 'common/js/config'
import {playerMixin} from 'common/js/mixin'
import Lyric from 'lyric-parser'
import Scroll from 'base/scroll/scroll'
import Playlist from 'components/playlist/playlist'
export default {
  name: 'Player',
  mixins: [playerMixin],
  data () {
    return {
      songReady: false,
      currentTime: 0,
      radius: 64,
      currentLyric: null,
      currentLineNum: 0,
      currentShow: 'cd',
      touch: {},
      playingLyric: ''
    }
  },
  computed: {
    ...mapGetters([
      // 'playList',
      'fullScreen',
      // 'currentSong',
      'playing',
      'currentIndex'
      // 'mode',
      // 'sequenceList'
    ]),
    // iconMode () {
    //   return this.mode === playMode.sequence ? 'icon-sequence' : this.mode === playMode.loop ? 'icon-loop' : 'icon-random'
    // },
    addCls () {
      return this.playing ? 'playing' : 'playing paused'
    },
    iconPlay () {
      return this.playing ? 'icon-pause' : 'icon-play'
    },
    iconMiniPlay () {
      return this.playing ? 'icon-pause-mini' : 'icon-play-mini'
    },
    disableCls () {
      return this.songReady ? 'disable' : ''
    },
    durTime () {
      return this._pad(this.formate(this.currentSong.duration))
    },
    percent () {
      return this.currentTime / this.currentSong.duration
    }
  },
  methods: {
    closePlaylist () {
      this.$refs.playlist.hide()
    },
    showPlaylist () {
      this.$refs.playlist.show()
    },
    middleTouchStart (e) {
      this.touch.initialized = true
      this.touch.move = false
      this.touch.startX = e.targetTouches[0].pageX
      this.touch.startY = e.targetTouches[0].pageY
    },
    middleTouchMove (e) {
      if (!this.touch.initialized) return
      if (!this.touch.move) {
        this.touch.move = true
      }
      let deltaX = e.targetTouches[0].pageX - this.touch.startX
      let deltaY = e.targetTouches[0].pageY - this.touch.startY
      if (Math.abs(deltaX) < Math.abs(deltaY)) return

      const left = this.currentShow === 'cd' ? 0 : -window.innerWidth
      const offsetWidth = Math.min(0, Math.max(-window.innerWidth, left + deltaX))
      this.touch.percent = Math.abs(offsetWidth / window.innerWidth)
      this.$refs.middleL.style.opacity = 1 - this.touch.percent
      this.$refs.middleL.style.transitionDuration = 0
      this.$refs.middleLyric.style.transform = `translate3d(${offsetWidth}px, 0, 0)`
      this.$refs.middleLyric.style.transitionDuration = 0
    },
    middleTouchEnd () {
      this.touch.initialized = false
      if (!this.touch.move) return
      let offsetWidth
      let opacity
      if (this.currentShow === 'cd') {
        if (this.touch.percent > 0.1) {
          offsetWidth = -window.innerWidth
          opacity = 0
          this.currentShow = 'lyric'
        } else {
          offsetWidth = 0
          opacity = 1
        }
      } else {
        if (this.touch.percent < 0.9) {
          offsetWidth = 0
          opacity = 1
          this.currentShow = 'cd'
        } else {
          offsetWidth = -window.innerWidth
          opacity = 0
        }
      }
      const time = '300'
      this.$refs.middleLyric.style.transform = `translate3d(${offsetWidth}px, 0, 0)`
      this.$refs.middleLyric.style.transitionDuration = `${time}ms`
      this.$refs.middleL.style.opacity = opacity
      this.$refs.middleL.style.transitionDuration = `${time}ms`
    },
    // changeMode () {
    //   const mode = (this.mode + 1) % 3
    //   this.setPlayMode(mode)
    //   let list = null
    //   if (this.mode === playMode.random) {
    //     list = shuffle(this.sequenceList)
    //   } else {
    //     list = this.sequenceList
    //   }
    //   this.resetCurrentIndex(list)
    //   this.setPlayList(list)
    // },
    // resetCurrentIndex (list) {
    //   let index = list.findIndex((item) => {
    //     return item.id === this.currentSong.id
    //   })
    //   this.setCurrentIndex(index)
    // },
    changePercent (percent) {
      const currentTime = this.$refs.audio.duration * percent
      this.$refs.audio.currentTime = currentTime
      if (this.currentLyric) {
        this.currentLyric.seek(currentTime * 1000)
      }
    },
    back () {
      this.setFullScreen(false)
    },
    showFullScreen () {
      this.setFullScreen(true)
    },
    changePlay () {
      // if (!this.songReady) return
      this.setPlayState(!this.playing)
      if (this.currentLyric) {
        this.currentLyric.togglePlay()
      }
    },
    endSong () {
      if (this.mode === playMode.loop) {
        this.loop()
      } else {
        this.nextSong()
      }
    },
    loop () {
      this.$refs.audio.currentTime = 0
      this.$refs.audio.play()
      if (this.currentLyric) {
        this.currentLyric.seek(0)
      }
    },
    nextSong () {
      // if (!this.songReady) return
      // 这里没有网络歌曲,暂时模拟
      this.savePlayHistory(this.currentSong)
      if (this.playList.length === 1) {
        this.loop()
      } else {
        let index = this.currentIndex + 1
        if (index === this.playList.length) {
          index = 0
        }
        this.setCurrentIndex(index)
        if (!this.playing) {
          this.changePlay()
        }
      }
      // this.songReady = false
    },
    prevSong () {
      // if (!this.songReady) return
      if (this.playList.length === 1) {
        this.loop()
      } else {
        let index = this.currentIndex - 1
        if (index === -1) {
          index = this.playList.length - 1
        }
        this.setCurrentIndex(index)
        if (!this.playing) {
          this.changePlay()
        }
      }
      // this.songReady = false
    },
    canplay () {
      this.songReady = true
    },
    error () {
      this.songReady = true
    },
    updateTime (e) {
      this.currentTime = e.target.currentTime
    },
    formate (interval) {
      let minute = this._pad(Math.floor(interval / 60))
      let second = this._pad(Math.floor(interval % 60))
      return `${minute}:${second}`
    },
    _pad (num, n = 2) {
      let len = num.toString().length
      while (len < n) {
        num = '0' + num
        len++
      }
      return num
    },
    enter (el, done) {
      const {x, y, scale} = this._getAnimationPos()
      let animation = {
        '0%': {
          transform: `translate3d(${x}px, ${y}px, 0) scale(${scale})`
        },
        '60%': {
          transform: `translate3d(0, 0, 0) scale(1.1)`
        },
        '100%': {
          transform: `translate3d(0, 0, 0) scale(1.0)`
        }
      }
      animations.registerAnimation({
        name: 'move',
        animation,
        presets: {
          duration: 400,
          easing: 'linear'
        }
      })
      animations.runAnimation(this.$refs.cdWrapper, 'move', done)
    },
    afterEnter () {
      animations.unregisterAnimation('move')
      this.$refs.cdWrapper.style.animation = ''
    },
    leave (el, done) {
      const {x, y, scale} = this._getAnimationPos()
      this.$refs.cdWrapper.style.transition = 'all 0.4s'
      this.$refs.cdWrapper.style.transform = `translate3d(${x}px, ${y}px, 0) scale(${scale})`
      this.$refs.cdWrapper.addEventListener('transitionend', done)
    },
    afterLeave () {
      this.$refs.cdWrapper.style.animation = ''
      this.$refs.cdWrapper.style.transform = ''
    },
    _getAnimationPos () {
      const sPicWidth = 80
      const sPaddingLeft = 20
      const sPaddingBottom = 20
      const lPicWidth = window.innerWidth * 0.8
      const lPicPaddingTop = 160
      const x = -(window.innerWidth / 2 - sPaddingLeft - sPicWidth / 2)
      const y = window.innerHeight - lPicWidth / 2 - lPicPaddingTop - sPaddingBottom - sPicWidth / 2
      const scale = sPicWidth / lPicWidth
      return {x, y, scale}
    },
    getLyric () {
      this.currentSong.getLyric()
        .then((lyric) => {
          if (this.currentSong.lyric !== lyric) return
          this.currentLyric = new Lyric(lyric, this.handleLyric)
          if (this.playing) {
            this.currentLyric.play()
          }
        })
        .catch(() => {
          this.currentLyric = null
          this.playingLyric = ''
          this.currentLineNum = 0
        })
    },
    handleLyric ({lineNum, txt}) {
      this.currentLineNum = lineNum
      let lineEl = this.$refs.lineEls[lineNum - 5]
      if (lineNum > 5) {
        this.$refs.lyricList.scrollToElement(lineEl, 1000)
      } else {
        this.$refs.lyricList.scrollTo(0, 0, 1000)
      }
      this.playingLyric = txt
    },
    ...mapMutations({
      setFullScreen: 'SET_FULL_SCREEN'
      // setPlayState: 'SET_PLAYING_STATE',
      // setCurrentIndex: 'SET_CURRENT_INDEX',
      // setPlayMode: 'SET_PLAY_MODE',
      // setPlayList: 'SET_PLAYLIST'
    }),
    ...mapActions(['savePlayHistory'])
  },
  watch: {
    currentSong (newSong, oldSong) {
      if (!newSong.id) return
      if (newSong.id === oldSong.id) return
      if (this.currentLyric) {
        this.currentLyric.stop()
        this.currentTime = 0
        this.currentLineNum = 0
        this.playingLyric = ''
      }
      // clearTimeout(this.timer)
      // this.timer = setTimeout(() => {
      this.$refs.audio.play()
      this.getLyric()
      // }, 1000)
    },
    playing (newPlaying, oldPlaying) {
      const audio = this.$refs.audio
      this.$nextTick(() => {
        newPlaying ? audio.play() : audio.pause()
      })
    }
  },
  components: {
    ProgressBar,
    ProgressCircle,
    Scroll,
    Playlist
  }
}
</script>
<style lang="scss" scoped>
@import 'common/scss/variable.scss';
@import 'common/scss/mixin.scss';
.player{
  .player-normal{
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 100;
    background: $color-highlight-background;
    &.normal-enter-active, &.normal-leave-active{
      transition: all 0.4s;
      .top{
        transition: all 0.4s cubic-bezier(.17,.67,.83,.67);
      }
      .bottom{
        transition: all 0.4s cubic-bezier(.17,.67,.83,.67);
      }
  }
    &.normal-enter, &.normal-leave-to{
      opacity: 0;
      .top{
        transform: translate3d(0, -200px, 0);
      }
      .bottom{
        transform: translate3d(0, 200px, 0);
      }
    }
    .background{
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      img{
        background-size: cover;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        opacity: 0.6;
        z-index: -1;
        filter: blur(0.4rem);
      }
    }
    .top{
      margin-bottom: 0.5rem;
      .back{
        padding: 0.18rem;
        font-size: 0.44rem;
        color: $color-theme;
        transform: rotate(-90deg);
        position: absolute;
        left: 0.08rem;
        top: 0;
      }
      .title{
        width: 100%;
        height: 0.8rem;
        line-height: 0.8rem;
        font-size: 0.36rem;
        color: #fff;
        margin: 0 auto;
        text-align: center;
        padding: 0 0.8rem;
        white-space: nowrap;
        overflow: hidden;
        box-sizing: border-box;
        @include ellipse();
      }
      .subtitle{
        width: 100%;
        height: 0.4rem;
        line-height: 0.4rem;
        font-size: 0.28rem;
        text-align: center;
      }
    }
    .middle{
      position: fixed;
      top: 1.6rem;
      bottom: 2.4rem;
      width: 100%;
      white-space: nowrap;
      .middle-l{
        width: 100%;
        padding-top: 80%;
        vertical-align: top;
        height: 0;
        position: relative;
        display: inline-block;
        .cd-wrapper{
          position: absolute;
          left: 10%;
          top: 0;
          width: 80%;
          height: 100%;
          .cd{
            width: 100%;
            height: 100%;
            box-sizing: border-box;
            border: 0.2rem solid rgba(255,255,255,0.1);
            border-radius: 50%;
            img{
              width: 100%;
              height: 100%;
              border-radius: 50%;
              &.playing{
                animation: rotate 10s linear infinite ;
              }
              &.paused{
                animation-play-state: paused;
              }
            }
          }
        }
        .playing-lyric-wrapper{
          width: 100%;
          text-align: center;
          line-height: 0.64rem;
          font-size: $font-size-medium;
          margin: 40px auto 0 auto;
          white-space: normal;
          color: #31c27c;
        }
      }
      .middle-r{
        display: inline-block;
        width: 100%;
        height: 90%;
        vertical-align: top;
        overflow: hidden;
        z-index: 999;
        .scroll-lyric{
          width: 100%;
          height: 100%;
        }
        .lyric-wrapper{
          width: 80%;
          margin: 0 auto;
          overflow: hidden;
          text-align: center;
          .text{
            line-height: 0.64rem;
            color: $color-text-l;
            font-size: $font-size-medium;
            &.current{
              color: #31c27c;
            }
          }
        }
      }
    }
    .bottom{
      position: absolute;
      bottom: 0.5rem;
      width: 100%;
      // touch-action: none;
      .dot-wrapper{
        text-align: center;
        font-size: 0;
        .dot{
          display: inline-block;
          vertical-align: middle;
          width: 0.16rem;
          height: 0.16rem;
          border-radius: 50%;
          background: $color-text-l;
          margin: 0 0.08rem;
          &.active{
            width: 0.4rem;
            border-radius: 0.1rem;
            background: $color-text-ll;
          }
        }
      }
      .progress-wrapper{
        display: flex;
        align-items: center;
        margin: 0 auto;
        padding: 0.2rem 0;
        width: 80%;
        .time{
          width: 0.6rem;
          line-height: 0.6rem;
          color: #fff;
          font-size: 0.24rem;
          white-space: nowrap;
          &:nth-of-type(1){
            margin-right: 0.2rem;
          }
          &:nth-of-type(2){
            margin-left: 0.2rem;
          }
        }
        .progress-bar-wrapper{
          flex: 1;
        }
      }
      .operators{
        display: flex;
        align-items: center;
        .icon{
          flex: 1;
          color: $color-theme;
          font-size: 0.6rem;
        }
        .i-left{
          text-align: right;
        }
        .i-center{
          text-align: center;
          font-size: 0.8rem;
          padding: 0 0.4rem;
        }
        .i-right{
          text-align: left;
          .icon-favorite{
            color: red;
          }
        }
      }
    }

  }
  .player-mini{
    display: flex;
    align-items: center;
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 1.2rem;
    background: $color-highlight-background;
    z-index: 180;
    &.mini-enter-active, &.mini-leave-active{
      transition: all 0.4s;
    }
    &.mini-enter, &.mini-leave-to{
      opacity: 0;
    }
    .icon{
      width: 0.8rem;
      height: 0.8rem;
      padding: 0 0.1rem 0 0.2rem;
      img{
        border-radius: 50%;
        width: 100%;
        height: 100%;
        &.playing{
          animation: rotate 10s linear infinite ;
        }
        &.paused{
          animation-play-state: paused;
        }
      }
    }
    .text{
      display: flex;
      justify-content: center;
      flex-direction: column;
      flex: 1;
      line-height: 0.4rem;
      overflow: hidden;
      h2{
        font-size: 0.28rem;
        margin-bottom: 0.02rem;
        color: #fff;
        @include ellipse();
      }
      p{
        font-size: 0.24rem;
        @include ellipse();
        color: $color-text-d;
      }
    }
    .control{
      width: 0.6rem;
      padding: 0 0.2rem;
      .progress-circle{
        position: relative;
        .icon-mini{
          font-size: 0.64rem;
          position: absolute;
          top: 0.23rem;
          left: 0;
          color: $color-theme-d;
        }
      }
      .icon-playlist{
        font-size: 0.6rem;
        color: $color-theme-d;
        position: relative;
        top: -0.08rem;
      }
    }
  }
}
@keyframes rotate {
    0%{
      transform: rotate(0)
    }
    100%{
      transform: rotate(360deg)
    }
}
</style>
